<?php
/**
* @Author Amanjeev (AJ) 
* @ingroup Extensions
* @Category Revision, find oldest revision of a particular text (markup)
*/

//Hook to create a tab
$wgHooks['SkinTemplateContentActions'][] = 'histrikiTab';
function histrikiTab( &$content_actions) {
    global $wgTitle;
    $content_actions[] = array(
        'text' => 'Histriki',
        'href' => $wgTitle->getFullURL( 'action=findold' ), //Set URL
    );
    return true;
}

//function to get string before, strstr() gives the string after needle.
//...before V 5.3 :(
function strstrb($h,$n){
    return strrev(array_pop(explode($n,strrev($h))));
}


$wgHooks['UnknownAction'][] = 'findOld'; //Hook to link action to the tab
//Action to be performed
function findOld ($action, $article) {
    global $wgOut; //Ouput object
    global $wgArticle; //Current Article object
    
    //Form to submit text
    $form = "<form action='$_SELF' method='POST'>
            <textarea name='findoldtext'>$_POST[findoldtext]</textarea>
            <input type='submit' name='Submit'/>
            </form>";

    //Page text with title and instructions
    $histriki_page_text = "<h1>Histriki Page for ".$article->getTitle()."</h1><p>Please select the markup text from the bottom, copy it, paste it in the text box and press 'Submit Query'. You will get the link to the oldest revision, that text is from.</p>";
    $wgOut->addHTML($histriki_page_text);

    if(isset($_POST['Submit'])) {
        //Build one of the conditions to search the table 'text'
        $oldtextsearch = 'old_text like "%'.$_POST['findoldtext'].'%"';

       //Database calls to get the oldest revision
       $dbr = &wfGetDB(DB_SLAVE);
       $res = $dbr->select('text',                             
                     array('old_id', 'old_text'),               
                     $oldtextsearch, 
                     '',                                         
                     array('ORDER BY' => 'old_id')); 

       $row = $dbr->fetchObject($res);
       $oldestid = $row->old_id; //get the first old_id (i.e. the lowest/oldest)
       $subject = $_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']; //get the current full URL
       $canon = strstrb($subject, '?');//get a particular part (right before ?)

       $result_text = "<div style='font-size:1.8em; background-color:#FFDCBF; border:1px solid; width:60%; margin: 6px; padding:6px;'>";
       $wgOut->addHTML($result_text."<a  href='http://".$canon."?title=".$article->getTitle()."&oldid=".$oldestid."' target='_blank'>This is the link to the oldest Revision with this text.</a></div>");
       
       $wgOut->addHTML($form); 
       $wgOut->addHTML($article->fetchContent()); //display the markup text
       return false;
    }

    else {
        if ($action == 'findold') {
           
            $wgOut->addHTML($form);
            $wgOut->addHTML($article->fetchContent());
            return false;
        }
        else {
            return true;
        }
    }
}
